import datetime
import random

from flask import session
from flask_script import Manager
from flask_migrate import MigrateCommand
from info import create_app

# 创建应用
app = create_app("dev")

# 创建管理器
mgr = Manager(app)

# 生成迁移命令
mgr.add_command("mc", MigrateCommand)


# 将函数变为命令
# @mgr.command
# def demo():
#     print("demo")


# 将有参数的函数变成命令, 使用@mgr.option
@mgr.option("-u", dest="username")
@mgr.option("-p", dest="password")
def create_superuser(username, password):
    """
    创建管理员账号
    """
    from info import db
    from info.models import User
    user = User()
    user.mobile = username
    user.nick_name = username
    user.password = password
    user.is_admin = True
    # 添加到事务中
    db.session.add(user)
    try:
        db.session.commit()
    except BaseException as e:
        db.session.rollback()
        app.logger.error("数据库错误: %s" % e)

    app.logger.info("管理员创建成功")


@mgr.command
def add_test_user():
    """添加测试用户"""
    from info import db
    from info.models import User
    users = []

    now = datetime.datetime.now()
    for num in range(0, 10000):
        try:
            user = User()
            user.nick_name = "%011d" % num
            user.mobile = "%011d" % num
            user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b990b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829"
            # 生成随机的用户注册时间
            user.create_time = now - datetime.timedelta(seconds=random.randint(0, 2678400))
            users.append(user)
            print(user.mobile)
        except Exception as e:
            print(e)

    db.session.add_all(users)
    db.session.commit()
    print("OK")


if __name__ == '__main__':
    mgr.run()
